package com.efounder.zone.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.util.ToastUtil;
import com.efounder.zone.R;
import com.efounder.zone.bean.BlackUserBean;
import com.efounder.zone.util.ZoneRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.LogUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 空间黑名单
 */

public class ZoneBlackListActivity extends BaseActivity {

    private static final String TAG = "ZoneBlackListActivity";
    private SmartRefreshLayout refreshLayout;
    private ClassicsHeader classicHeader;
    private RecyclerView recyclerView;

    private ImageView ivBack;
    private TextView tvTitle;
    private BlackListAdapter mAdapter;
    private List<BlackUserBean> mDatas;

    private int page = 1;

    public static void start(Context context) {
        Intent starter = new Intent(context, ZoneBlackListActivity.class);
        // starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mobile_zone_activity_blacklist);
//        EventBus.getDefault().register(this);
        initView();
        initData();

    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        classicHeader = (ClassicsHeader) findViewById(R.id.classic_header);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }


    private void initData() {
        tvTitle.setText(R.string.zone_blacklist);
        mDatas = new ArrayList<>();
        mAdapter = new BlackListAdapter(this, R.layout.mobile_zone_item_blacklist, mDatas);
        recyclerView.setAdapter(mAdapter);

//        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                page += 1;
//                loadData(true);
//            }
//
//            @Override
//            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                page = 1;
//                mDatas.clear();
//                mAdapter.notifyDataSetChanged();
//                loadData(false);
//            }
//        });
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mDatas.clear();
                mAdapter.notifyDataSetChanged();
                loadData(false);
            }
        });

        loadData(false);
    }

    /**
     * 请求详情数据
     */

    private void loadData(final boolean isLoadMore) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));

        ZoneRequestUtil.getCommonRequest(TAG, "black/getBlackList", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                finishLoad(isLoadMore);
                try {
                    LogUtils.i(response);
                    JSONArray array = JSONArray.fromObject(response);
                    if (array != null && array.size() > 0) {
                        for (int i = 0; i < array.size(); i++) {
                            int userId = array.getInt(i);
                            User user = WeChatDBManager.getInstance().getOneUserById(userId);
                            BlackUserBean blackUserBean = new BlackUserBean.Builder()
                                    .isBlack(true).userName(user.getNickName())
                                    .avatar(user.getAvatar())
                                    .useId(userId + "").build();
                            mDatas.add(blackUserBean);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(ZoneBlackListActivity.this, R.string.common_text_http_request_fail_abnormal);
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(String error) {
                finishLoad(isLoadMore);
                ToastUtil.showToast(ZoneBlackListActivity.this, R.string.common_text_http_request_fail_abnormal);
            }
        });

    }

    private void finishLoad(boolean isLoadMore) {
        if (isLoadMore) {
            refreshLayout.finishLoadMore(100);
        } else {
            refreshLayout.finishRefresh(100);
        }
    }


    @Override
    public void finish() {
        super.finish();
        //EventBus.getDefault().unregister(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public static class BlackListAdapter extends CommonAdapter<BlackUserBean> {
        private Context context;
        private List<BlackUserBean> datas;

        public BlackListAdapter(Context context, int layoutId, List<BlackUserBean> datas) {
            super(context, layoutId, datas);
            this.context = context;
            this.datas = datas;
        }

        @Override
        protected void convert(ViewHolder holder, final BlackUserBean blackUserBean, int position) {
            ImageView ivIcon;
            TextView tvName;
            TextView info;
            Button btAccept;

            ivIcon = (ImageView) holder.getView(R.id.iv_icon);
            tvName = (TextView) holder.getView(R.id.tv_name);
            info = (TextView) holder.getView(R.id.info);
            btAccept = (Button) holder.getView(R.id.bt_accept);
            LXGlideImageLoader.getInstance().showRoundUserAvatar(context, ivIcon, blackUserBean.getAvatar()
                    , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
            tvName.setText(blackUserBean.getUserName());
            info.setText(mContext.getString(R.string.showNumberText) + " " + blackUserBean.getUseId());
            btAccept.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeFromBlackList(blackUserBean);
                }
            });


        }

        private void removeFromBlackList(final BlackUserBean blackUserBean) {
            HashMap<String, String> params = new HashMap<>();
            params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
            params.put("blackUserid", blackUserBean.getUseId());
            ZoneRequestUtil.getCommonRequest(TAG, "black/delete", params, new ZoneRequestUtil.ZoneRequestCallback() {
                @Override
                public void onSuccess(String response) {

                    try {
                        LogUtils.i(response);
                        JSONObject jsonObject = JSONObject.fromObject(response);
                        if (jsonObject.optString("status", "").equals("111001")) {

                            ToastUtil.showToast(mContext, R.string.zone_remove_success);
                            datas.remove(blackUserBean);
                            notifyDataSetChanged();
                        } else {
                            ToastUtil.showToast(mContext, R.string.zone_remove_fail);
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(mContext, R.string.common_text_http_request_fail_abnormal);
                    }
                }

                @Override
                public void onFail(String error) {

                    ToastUtil.showToast(mContext, R.string.common_text_http_request_fail_abnormal);
                }
            });
        }
    }
}
